package net.aiion.weave.impl.painters.stream;

import java.io.ByteArrayOutputStream;
import java.io.IOException;

import net.aiion.weave.spi.injection.annotations.Inject;
import net.aiion.weave.spi.painters.PaintBrush;
import net.aiion.weave.spi.painters.PaintException;
import net.aiion.weave.spi.painters.PainterService;
import net.aiion.weave.spi.painters.stream.StreamPaintBrush;

public abstract class AbstractStreamBrush implements StreamPaintBrush
{
    @Inject
    private PainterService painterService;

    private ByteArrayOutputStream outputStream;

    public AbstractStreamBrush() {
    }

    @Override
    public ByteArrayOutputStream getOutputStream() {
        if (outputStream == null) {
            outputStream = new ByteArrayOutputStream();
        }
        return outputStream;
    }

    @Override
    public void setOutputStream(final ByteArrayOutputStream aOutputStream) {
        outputStream = aOutputStream;
    }

    @Override
    public void paintComponent(final Object aNamed) {
        paintBrush(painterService.paintComponent(aNamed));
    }

    @Override
    public void paintBrush(final PaintBrush aBrush) {
        if (aBrush instanceof StreamPaintBrush) {
            try {
                getOutputStream().write(((StreamPaintBrush) aBrush).getOutputStream().toByteArray());
            } catch (final IOException e) {
                throw new PaintException(e);
            }
        }
    }

    @Override
    public boolean hasPainted() {
        return getOutputStream().size() > 0;
    }
}
